package com.loan.inceptor;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.loan.model.Staff;
import com.loan.service.StaffService;
import com.loan.service.UserService;
import com.loan.util.MD5Util;
import com.loan.util.Str;

public class ShiroRealm extends AuthorizingRealm{
	private static UserService user = new UserService();
	private static StaffService staff = new StaffService();

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String pass = "";
		for(char c : token.getPassword()){
			pass += c;
		} 
		String[] host = token.getHost().split(",");
		String type = host[0];
		int cid = Integer.valueOf(host[1]); 
		Object obj = Str.eq(type,"backend")?staff.checkLogin(cid,token.getUsername(),MD5Util.encrypt(pass.toString())):user.checkLogin(cid,token.getUsername(),MD5Util.encrypt(pass.toString()));
		if (obj!=null) {
			return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), "");
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<String>();
        Staff s = staff.findByMobile(principals.getPrimaryPrincipal().toString());
        if(s!=null){ 
        	for(String role : s.getRole().split(",")){
                roles.add(role);
        	}
        }
        //	添加用户角色
        info.addRoles(roles);
        return info;
	}
}
